package com.etheart.lyric.htmlparser.service.baidu;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.etheart.framework.core.util.RegexUtils;
import com.etheart.lyric.htmlparser.util.HtmlparserUtils;

public class BaiduSingerMapParserService {
	
	public BaiduSingerMapParserService(String dir) {
		if (map.isEmpty()) {
			map = initSexMap(dir);
		}
	}

	private static Map<String, String[]> map = new HashMap<String, String[]>();
	
	private Map<String, String[]> initSexMap(String dir) {
	//	D:\qqmusic\巨鲸\mirror\artist
		File file = new File(dir);
		FilenameFilter filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (name.indexOf("index")!=-1) {
					return true;
				}
				return false;
			}
		};
		
		File[] files = file.listFiles(filter);
		for (File f : files) {
			String sexstr = RegexUtils.getMatcheGroup(".*s=(.*)", f.getName());
			String sex;
			if (sexstr.startsWith("w")) {
				sex = "女";
			}else if (sexstr.startsWith("m")) {
				sex="男";
			} else {
				sex="组合";
			}
			
			//地区
			String areaStr = RegexUtils.getMatcheGroup(".*area=(.*)", f.getName());
			String area="";
			if (areaStr.startsWith("mainland")) {
				area = "大陆";
			}else if (areaStr.startsWith("hktw")) {
				area="港台";
			} else if(areaStr.startsWith("japkor")){
				area="日韩";
			}else if (areaStr.startsWith("eur")) {
				area = "欧美";
			}else if (areaStr.startsWith("other")) {
				area = "其他";
			}
			
			
			try {
				Parser parser = HtmlparserUtils.getParser(f);
				parseSingerList(parser,map,sex,area);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 		}
		return map;
	}

	private void parseSingerList(Parser parser, Map<String, String[]> map,String sex,String area) {
		NodeFilter nodeFilter = new TagNameFilter("a");
		try {
			NodeList nodeList = parser.parse(nodeFilter);
			for (int i = 0; i < nodeList.size(); i++) {
				String html = nodeList.elementAt(i).toHtml();
				if (html.indexOf("/artist/info.php?singerid=")!=-1) {
					String id = RegexUtils.getMatcheGroup(".*singerid=([^\"]*)\".*", html);
					map.put(id, new String[]{sex,area});
				}
			}
		} catch (ParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Map<String, String[]> getSingerMap() {
		// TODO Auto-generated method stub
		return map;
	}

	
	
}
